package cn.codesea.housework_user.ui;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.codesea.housework_user.R;
import cn.codesea.housework_user.adapter.HomeRcvAdapter;
import cn.codesea.housework_user.adapter.listener.OnOperationClickListener;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickActivityListener;
import cn.codesea.housework_user.adapter.listener.OnRecyclerItemClickOrderListener;
import cn.codesea.housework_user.adapter.OrderRcvAdapter;
import cn.codesea.housework_user.entity.Activity;
import cn.codesea.housework_user.entity.Order;
import cn.codesea.housework_user.entity.User;
import cn.codesea.housework_user.net.ServiceGenerator;
import cn.codesea.housework_user.net.data.Result;
import cn.codesea.housework_user.net.service.ActivityService;
import cn.codesea.housework_user.net.service.OrderService;
import cn.codesea.housework_user.ui.component.EvaDialog;
import cn.codesea.housework_user.utils.DateUtil;
import cn.codesea.housework_user.utils.SPUtil;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class Tab2MineOldFragment extends Fragment {

    @BindView(R.id.order_waiting_ll)
    LinearLayout order_waiting_ll;// 待接单
    @BindView(R.id.order_waiting_tv)
    TextView order_waiting_tv;
    @BindView(R.id.order_waiting_iv)
    ImageView order_waiting_iv;
    @BindView(R.id.order_received_ll)
    LinearLayout order_received_ll;// 已接单
    @BindView(R.id.order_received_tv)
    TextView order_received_tv;
    @BindView(R.id.order_received_iv)
    ImageView order_received_iv;
    @BindView(R.id.order_processing_ll)
    LinearLayout order_processing_ll;// 进行中
    @BindView(R.id.order_processing_tv)
    TextView order_processing_tv;
    @BindView(R.id.order_processing_iv)
    ImageView order_processing_iv;
    @BindView(R.id.order_end_ll)
    LinearLayout order_end_ll;// 已结束
    @BindView(R.id.order_end_tv)
    TextView order_end_tv;
    @BindView(R.id.order_end_iv)
    ImageView order_end_iv;

    @BindView(R.id.order_rcv)
    RecyclerView order_rcv;
    List<Order> orders = new ArrayList<>();
    OrderRcvAdapter adapter;
    LinearLayoutManager mLinearLayoutManager;


    @BindView(R.id.more_order_tv)
    TextView more_order_tv;

    @BindView(R.id.activity_rcv)
    RecyclerView activity_rcv;
    List<Activity> acts = new ArrayList<>();
    HomeRcvAdapter mHomeRcvAdapter;
    LinearLayoutManager m_ActivityLinearLayoutManager;

    @BindView(R.id.name_tv)
    TextView name_tv;
    @BindView(R.id.modify_tv)
    TextView modify_tv;
    @BindView(R.id.logout_tv)
    TextView logout_tv;

    User older;

    int index = 0;

    @BindView(R.id.more_activity_tv)
    TextView more_activity_tv;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_tab2_mine_old,container,false);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        init();
    }

    @Override
    public void onResume() {
        super.onResume();
        updateRecyclerView();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(!hidden){
            updateRecyclerView();
        }
    }

    private void init(){
        initData();
        initView();
    }

    private void initData(){

        older = (User)getActivity().getIntent().getSerializableExtra("older");
        if (older == null){// older 为null 时，表示该页面并非其它activity跳转而来
            older = new Gson().fromJson(SPUtil.get(getActivity(),SPUtil.USER,""),User.class);
            logout_tv.setVisibility(View.VISIBLE);
        }

    }

    public void updateRecyclerView(){
        ActivityService activityService = ServiceGenerator.createService(ActivityService.class);
        Call<Result> call = activityService.joinActsSearch(older.getUserid());
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                Result result = response.body();
                Type type = new TypeToken<List<Activity>>(){}.getType();
                acts.clear();
//                acts.addAll((List<Activity>)new Gson().fromJson(String.valueOf(result.getRes()),type));

                // 这里只显示2个
                List<Activity> list = new Gson().fromJson(String.valueOf(result.getRes()),type);
                if (list.size()>2){
                    acts.add(list.get(0));
                    acts.add(list.get(1));
                }else {
                    acts.addAll(list);
                }

                mHomeRcvAdapter.notifyDataSetChanged();
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });
    }

    private void initView(){

        name_tv.setText(older.getName());

        adapter = new OrderRcvAdapter(getActivity(),orders);
        adapter.setRecyclerItemClickListener(new OnRecyclerItemClickOrderListener() {
            @Override
            public void onItemClick(int Position, List<Order> list) {
//                startActivity(new Intent(getActivity(),AcActivity.class).putExtra("data",mDatas.get(Position)));
            }
        });
        adapter.setOperationClickListener(new OnOperationClickListener(){
            @Override
            public void onOperationClick(int position, List<Order> list) {
                Order order = list.get(position);
                int status = order.getStatus();
                final Map params = new HashMap();
                params.put("orderid",order.getOrderid());
                switch (status){
                    case 0:
                        params.put("operate",0);// 取消
                        break;
                    case 2:
                        params.put("operate",2);// 结束
                        params.put("endtime",DateUtil.getDateNow());
                        break;
                    case 3:
                        params.put("operate",3);// 评价
                        EvaDialog evaDialog = new EvaDialog(getActivity());
                        evaDialog.setSubmit(new EvaDialog.OnSubmitClickListener() {
                            @Override
                            public void onSubmitClick(String eva) {
                                params.put("evaluation",eva);
                                operate(params);
                            }
                        });
                        evaDialog.show();

                        return;
                     default:
                         break;
                }

                operate(params);

            }
        });
        mLinearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);

        order_rcv.setLayoutManager(mLinearLayoutManager);
        order_rcv.setAdapter(adapter);

        mHomeRcvAdapter = new HomeRcvAdapter(getActivity(),acts);
        mHomeRcvAdapter.setRecyclerItemClickListener(new OnRecyclerItemClickActivityListener() {
            @Override
            public void onItemClick(int Position, List<Activity> list) {
//                Toast.makeText(AcListActivity.this,"Position:"+ Position, Toast.LENGTH_SHORT).show();
                startActivity(new Intent(getActivity(),AcActivity.class).putExtra("act",acts.get(Position)));
            }
        });
        m_ActivityLinearLayoutManager = new LinearLayoutManager(getActivity(),LinearLayoutManager.VERTICAL,false);
        activity_rcv.setLayoutManager(m_ActivityLinearLayoutManager);
        activity_rcv.setAdapter(mHomeRcvAdapter);

        setTab(0);
    }

    /**
     * 对订单的网络操作
     * @param params
     */
    private void operate(Map params){
        OrderService service = ServiceGenerator.createService(OrderService.class);
        Call<Result> call = service.operateOrder(params);
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                operateResultProcess(response.body());
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });
    }

    @OnClick(R.id.modify_tv)
    public void modify_tv(){
        startActivity(new Intent(getActivity(),RegisterOldActivity.class).putExtra("type","update").putExtra("older",older));
    }

    @OnClick(R.id.order_waiting_ll)
    public void order_waiting_ll(){// 待接单
        setTab(0);
    }

    @OnClick(R.id.order_received_ll)
    public void order_received_ll(){// 已接单
        setTab(1);
    }

    @OnClick(R.id.order_processing_ll)
    public void order_processing_ll(){// 进行中
        setTab(2);
    }

    @OnClick(R.id.order_end_ll)
    public void order_end_ll(){// 已结束
        setTab(3);
    }

    /**
     * tab页选择
     */
    private void setTab(int index){
        this.index = index;
        this.orders.clear();// 清除数据
        adapter.notifyDataSetChanged();
        selChangeBg(index);// 处理背景
        updateRecyclerView(index);// 更新数据
    }

    /**
     *更新RecyclerView
     */
    private void updateRecyclerView(int index){
        OrderService service = ServiceGenerator.createService(OrderService.class);
        Map params = new HashMap();
        params.put("userid",older.getUserid());
        params.put("status",index);
        Call<Result> call = service.getOrders(params);
        call.enqueue(new Callback<Result>(){
            @Override
            public void onResponse(Call<Result> call, Response<Result> response) {
                resultProcess(response.body());
            }

            @Override
            public void onFailure(Call<Result> call, Throwable t) {

            }
        });
    }

    /**
     * 结果处理
     */
    public void resultProcess(Result result){
        Type type = new TypeToken<List<Order>>(){}.getType();
        List<Order> orders = new Gson().fromJson(String.valueOf(result.getRes()),type);

        // 这里只展示一个
        if (orders.size() >0){
            this.orders.clear();
            this.orders.add(orders.get(0));
            adapter.notifyDataSetChanged();
        }

    }

    /**
     * 操作（取消、结束、评价）结果处理
     */
    public void operateResultProcess(Result result){
        Toast.makeText(getActivity(),"操作成功！",Toast.LENGTH_SHORT).show();
        setTab(index);
    }

    /**
     * 选择tab
     * @param index
     */
    private void selChangeBg(int index){
        switch (index){
            case 0:
                order_waiting_ll.setBackgroundColor(getResources().getColor(R.color.primary));
                order_waiting_tv.setTextColor(getResources().getColor(R.color.white));
                order_waiting_iv.setImageResource(R.drawable.tab_1_white);

                order_received_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_received_tv.setTextColor(getResources().getColor(R.color.black));
                order_received_iv.setImageResource(R.drawable.tab_2_red);

                order_processing_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_processing_tv.setTextColor(getResources().getColor(R.color.black));
                order_processing_iv.setImageResource(R.drawable.tab_3_red);

                order_end_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_end_tv.setTextColor(getResources().getColor(R.color.black));
                order_end_iv.setImageResource(R.drawable.tab_4_red);

                break;
            case 1:
                order_waiting_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_waiting_tv.setTextColor(getResources().getColor(R.color.black));
                order_waiting_iv.setImageResource(R.drawable.tab_1_red);

                order_received_ll.setBackgroundColor(getResources().getColor(R.color.primary));
                order_received_tv.setTextColor(getResources().getColor(R.color.white));
                order_received_iv.setImageResource(R.drawable.tab_2_white);

                order_processing_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_processing_tv.setTextColor(getResources().getColor(R.color.black));
                order_processing_iv.setImageResource(R.drawable.tab_3_red);

                order_end_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_end_tv.setTextColor(getResources().getColor(R.color.black));
                order_end_iv.setImageResource(R.drawable.tab_4_red);

                break;
            case 2:
                order_waiting_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_waiting_tv.setTextColor(getResources().getColor(R.color.black));
                order_waiting_iv.setImageResource(R.drawable.tab_1_red);

                order_received_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_received_tv.setTextColor(getResources().getColor(R.color.black));
                order_received_iv.setImageResource(R.drawable.tab_2_red);

                order_processing_ll.setBackgroundColor(getResources().getColor(R.color.primary));
                order_processing_tv.setTextColor(getResources().getColor(R.color.white));
                order_processing_iv.setImageResource(R.drawable.tab_3_white);

                order_end_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_end_tv.setTextColor(getResources().getColor(R.color.black));
                order_end_iv.setImageResource(R.drawable.tab_4_red);
                break;
            case 3:
                order_waiting_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_waiting_tv.setTextColor(getResources().getColor(R.color.black));
                order_waiting_iv.setImageResource(R.drawable.tab_1_red);

                order_received_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_received_tv.setTextColor(getResources().getColor(R.color.black));
                order_received_iv.setImageResource(R.drawable.tab_2_red);

                order_processing_ll.setBackgroundColor(getResources().getColor(R.color.white));
                order_processing_tv.setTextColor(getResources().getColor(R.color.black));
                order_processing_iv.setImageResource(R.drawable.tab_3_red);

                order_end_ll.setBackgroundColor(getResources().getColor(R.color.primary));
                order_end_tv.setTextColor(getResources().getColor(R.color.white));
                order_end_iv.setImageResource(R.drawable.tab_4_white);
                break;
             default:
                 order_waiting_ll.setBackgroundColor(getResources().getColor(R.color.primary));
                 order_waiting_tv.setTextColor(getResources().getColor(R.color.white));
                 order_waiting_iv.setImageResource(R.drawable.tab_1_white);

                 order_received_ll.setBackgroundColor(getResources().getColor(R.color.white));
                 order_received_tv.setTextColor(getResources().getColor(R.color.black));
                 order_received_iv.setImageResource(R.drawable.tab_2_red);

                 order_processing_ll.setBackgroundColor(getResources().getColor(R.color.white));
                 order_processing_tv.setTextColor(getResources().getColor(R.color.black));
                 order_processing_iv.setImageResource(R.drawable.tab_3_red);

                 order_end_ll.setBackgroundColor(getResources().getColor(R.color.white));
                 order_end_tv.setTextColor(getResources().getColor(R.color.black));
                 order_end_iv.setImageResource(R.drawable.tab_4_red);
                 break;
        }
    }

    @OnClick(R.id.more_order_tv)
    public void more_order_tv(){
        startActivity(new Intent(getActivity(),OrderListActivity.class).putExtra("userid",older.getUserid()).putExtra("index",index));
    }

    @OnClick(R.id.more_activity_tv)
    public void more_activity_tv(){
        startActivity(new Intent(getActivity(),AcListActivity.class).putExtra("userid",older.getUserid()));
    }

    @OnClick(R.id.logout_tv)
    public void logout_tv(){
        // 测试
        SPUtil.put(getActivity(),SPUtil.LOG_STATE,"0");
        startActivity(new Intent(getActivity(),GuideActivity.class));
        getActivity().finish();
    }
}
